import {
  wxRequest
} from '../../../utils/server.js';
const _wxRequest = new wxRequest();
const app = getApp()

Page({
  data: {
    imgUrl: app.globalData.imgUrl,
    listStatus: false, //宫格为false 列表为ture  
    hasNextPage: false,
    uploadUrl: wx.getStorageSync('uploadUrl'),
    historyList: [],
    list: [],
    pageNo: 1,
    tabId: 1,
    sortType: 1,
    stoSortType: 1,
    keyword: '',
    catId: ''
  },

  onShow: function() {
    this.getKeywordList();
  },


  //筛选
  handleFilt: function(e) {
    var sortType = e.currentTarget.dataset.type;
    this.setData({
      sortType
    })
    this.getlist()
  },


  //店铺筛选
  handleStoreFilt: function(e) {
    var stoSortType = e.currentTarget.dataset.type;
    this.setData({
      stoSortType: stoSortType
    })
    this.getlist()
  },



  // tab切换
  checkTab(e) {
    var id = e.currentTarget.dataset.id
    this.setData({
      tabId: id,
      pageNo: 1,
      hasNextPage: false, //初始化
      catflag: false,
      catId: ''
    })
    this.getlist()
  },

  //跳转详情页
  toGoodsDetail(e) {
    var id = e.currentTarget.dataset.id
    console.log(e)
    wx: wx.navigateTo({
      url: '/pages/good/detail/index?id=' + id,
    })
  },

  toStoreDetail(e) {
    var id = e.currentTarget.dataset.id
    console.log(e)
    wx.navigateTo({
      url: '/pages/store/detail?id=' + id,
    })
  },

  //价格筛选
  handlePice() {
    var sortType = this.data.sortType;
    if (sortType == 4) {
      sortType = 5
    } else {
      sortType = 4
    }
    console.log(sortType, 'sortType')
    this.setData({
      sortType
    })
    this.getlist()
  },

  handletype() {
    this.setData({
      listStatus: !this.data.listStatus
    })
  },



  //查询列表
  getlist: function() {
    if (this.data.tabId == 1) {
      this.goodsRequest()
    } else {
      this.storeRequest()
    }
  },


  //商品请求
  goodsRequest: function() {
    _wxRequest.wxAjax({
      url: app.globalData.apiUrl + '/gds/goods/list?keyword=' + this.data.keyword + '&sortType=' + this.data.sortType + '&pageNo=' + this.data.pageNo + '&catId=' + this.data.catId,
      method: 'POST',
    }, (res) => {
      let list = res.list;
      if (this.data.pageNo !== 1) {
        list = this.data.list.concat(list);
      }

      this.setData({
        list: list,
        pageNo: res.page.pageNo,
        hasNextPage: res.page.hasNextPage,
      });
    })
  },


  //店铺请求
  storeRequest: function() { 
    this.setData({
      list: []
    })

      _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/org/protected/store/findList',
      method: 'POST',
      // contentType: 'application/x-www-form-urlencoded',
      data: {
        pageNo: this.data.pageNo,
        keyword: this.data.keyword,
        sortType: this.data.stoSortType,
        lng: this.data.selfLongitude || '', //经度
        lat: this.data.selfLatitude || '', //纬度 
      }
    }, (res) => {
      let list = res.list;

      if (list.length>0){
        if (this.data.pageNo !== 1) {
          list = this.data.list.concat(list);
        }

        list.map(item => {
          item.offInfoJson = JSON.parse(item.offInfoJson);
          item.content = item.content.trim()
          if (item.distance >= 1000) {
            item.distanceText = (item.distance / 1000).toFixed(1) + 'km'
          } else if (item.distance > 0) {
            item.distanceText = Math.ceil(item.distance) + 'm'
          } else {
            item.distanceText = '未知'
          }
        })

        this.setData({
          list: list,
          pageNo: res.page.pageNo,
          hasNextPage: res.page.hasNextPage,
        });
      }

    })
  },


  //下拉刷新
  onPullDownRefresh: function() {
    this.refreshData();
    wx.stopPullDownRefresh()
  },

  refreshData: function() {
    this.setData({
      pageNo: 1
    })
    this.getlist();
  },

  //触底时，加载更多
  onReachBottom: function() {
    if (this.data.hasNextPage) {
      this.setData({
        pageNo: this.data.pageNo + 1
      });
      this.getlist();
    }
  },

  //搜索关键词
  seachInputConfirm: function(e) {
    var historyList = this.data.historyList || [],
      str = JSON.stringify(historyList),
      val = e.detail.value,
      historyItem = historyList
    if (str.indexOf(val) < 0) {
      historyItem = historyList.concat(val)
      wx.setStorageSync('historyItem', historyItem)
    }

    this.setData({
      historyList: historyItem,
      pageNo: 1,
      keyword: e.detail.value
    })

    this.addKeyword();
    this.getlist();
  },
  
  seachBtn: function () {
    this.setData({
      pageNo: 1,
      keyword: this.data.keyword
    })

    this.addKeyword()
    this.getlist();
  },

  seachInputVal: function(e) {
    this.setData({
      keyword: e.detail.value
    })
  },

  //清空
  clearInput: function() {
    this.setData({
      keyword: ''
    })
    this.getKeywordList();
    this.getlist();
  },

  //快速搜索
  fastSearch: function(e) {
    var item = e.currentTarget.dataset.item;
    this.setData({
      keyword: item
    })
    this.getlist()
  },

  //删除历史搜索
  // hisSearchDel: function() {
  //   var that = this
  //   wx.showModal({
  //     title: '提示',
  //     confirmText: '确定',
  //     cancelText: '取消',
  //     content: '确定删除历史记录',
  //     success: function(res) {
  //       if (res.confirm) {
  //         wx.removeStorageSync('historyItem')
  //         that.setData({
  //           historyList: []
  //         })
  //       }
  //     }
  //   })
  // },


  // 分类
  handleCat: function(e) {
    var that = this;
    var sortType = e.currentTarget.dataset.type;
    this.setData({
      catflag: true,
      sortType
    })

    that.getCat()
  },

  getCat: function() {
    _wxRequest.wxAjax({
      url: app.globalData.apiUrl + "/gds/goods/findGoodsCat",
      method: 'POST',
      data: {}
    }, (res) => {
      console.log(res, '分类')
      this.setData({
        catlist: res.list
      })
    })
  },

  //选择分类
  handleCatItem: function(e) {
    var code = e.currentTarget.dataset.code;
    this.setData({
      catId: code,
      catflag: false,
    })
    this.getlist()
  },


  //需要用户授权获取位置
  getuserLocation: function() {
    var that = this;
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.userLocation']) {
          wx.openSetting({
            success: (response) => {
              wx.getLocation({
                success: function(res) {
                  var latitude = res.latitude;
                  var longitude = res.longitude;
                  that.setData({
                    selfLongitude: longitude, //经度
                    selfLatitude: latitude, //纬度        
                  });
                  if (that.data.storeflage) {
                    that.storeRequest()
                  }
                }
              })
            }
          })
        }
      }
    })
  },


  // 

  //获取关键词列表
  getKeywordList:function(){
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + "/odr/protected/customerKeyword/list",
      method: 'POST',
      data: {}
    }, (res) => {
      console.log(res,'list')
      this.setData({
        historyList:res.list
      })
    })
  },


  //添加关键词列表
  addKeyword: function () {
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + "/odr/protected/customerKeyword/save",
      method: 'POST',
      data: {
        keyword: this.data.keyword
      }
    }, (res) => {
      console.log(res, 'list')
      this.setData({
        historyList: res.list
      })
    })
  },


    //删除关键词列表
  delKeyword: function (e) {
    var id = e.currentTarget.dataset.id;
    


    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + "/odr/protected/customerKeyword/delete?keyword=你好",
      method: 'POST',
      data: { 
        id
      }
    }, (res) => {
      console.log(res, 'list')
      this.setData({
        historyList: res.list
      })
      this.getKeywordList()
    })
  }




})